<template>
  <div class="app-container">
    <u-page title="优惠券管理">

      <div slot="header">
        <el-button type="primary" icon="el-icon-plus" @click="handleOpen">
          {{ textMap['create'] }}
        </el-button>
      </div>

      <u-filtered>
        <el-form :inline="true" :model="listQuery" class="search-form">
          <el-form-item label="优惠券分组" prop="group">
            <group v-model="listQuery.groupId" width="160px" />
          </el-form-item>
          <el-form-item label="优惠券名称" prop="name">
            <el-input v-model="listQuery.name" placeholder="优惠券名称" clearable style="width: 170px" />
          </el-form-item>

          <el-form-item label="有效期起始时间范围" prop="beginValidityDate">
            <u-date-time-picker v-model="listQuery.beginValidityDate" value-format="yyyy-MM-dd HH:mm:ss" @change="changeBeginValidityDate" />
          </el-form-item>
          <el-form-item label="创建时间" prop="creatDate">
            <u-date-time-picker v-model="creatDate" @change="changeDate" />
          </el-form-item>
          <el-form-item label="模板ID" prop="templateId">
            <el-input v-model="listQuery.templateId" placeholder="通联模板ID" style="width: 130px" clearable />
          </el-form-item>
          <el-form-item label="模板状态" prop="disabled">
            <el-select v-model="listQuery.disabled" placeholder="请选择状态" class="disabled" clearable>
              <el-option v-for="item in disabledList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="hdlFilter">搜索</el-button>
          </el-form-item>
        </el-form>
      </u-filtered>

      <el-tabs v-model="tabActive" type="border-card" @tab-click="handleClick">
        <el-tab-pane label="全部" name="all">
          <u-table
            :data="list"
            :loading="listLoading"
            :options="listOptions"
            :columns="columns"
            :pagination.sync="listQuery"
            :fetch="hdlList"
            @selection-change="hdlSelectChange"
          >
            <template v-slot:right>
              <el-table-column label="操作" align="center" fixed="right">
                <template slot-scope="{ row }">
                  <el-button type="text" @click="handleEdit(row)">编辑</el-button>
                  <el-dropdown>
                    <el-button type="text">更多</el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="hdlDelete(row.id, row.name)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </template>
          </u-table>
        </el-tab-pane>
        <el-tab-pane label="发放中" name="first">
          <u-table
            :data="list"
            :loading="listLoading"
            :options="listOptions"
            :columns="columns"
            :pagination.sync="listQuery"
            :fetch="hdlList"
            @selection-change="hdlSelectChange"
          >
            <template v-slot:right>
              <el-table-column label="操作" align="center" fixed="right">
                <template slot-scope="{ row }">
                  <el-button type="text" @click="handleEdit(row)">编辑</el-button>
                  <el-dropdown>
                    <el-button type="text">更多</el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="hdlDelete(row.id, row.name)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </template>
          </u-table>
        </el-tab-pane>
        <el-tab-pane label="未发放" name="second">
          <u-table
            :data="list"
            :loading="listLoading"
            :options="listOptions"
            :columns="columns"
            :pagination.sync="listQuery"
            :fetch="hdlList"
            @selection-change="hdlSelectChange"
          >
            <template v-slot:right>
              <el-table-column label="操作" align="center" fixed="right">
                <template slot-scope="{ row }">
                  <el-button type="text" @click="handleEdit(row)">编辑</el-button>
                  <el-dropdown>
                    <el-button type="text">更多</el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="hdlDelete(row.id, row.name)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </template>
          </u-table>
        </el-tab-pane>
        <el-tab-pane label="已领完" name="third">
          <u-table
            :data="list"
            :loading="listLoading"
            :options="listOptions"
            :columns="columns"
            :pagination.sync="listQuery"
            :fetch="hdlList"
            @selection-change="hdlSelectChange"
          >
            <template v-slot:right>
              <el-table-column label="操作" align="center" fixed="right">
                <template slot-scope="{ row }">
                  <el-button type="text" @click="handleEdit(row)">编辑</el-button>
                  <el-dropdown>
                    <el-button type="text">更多</el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="hdlDelete(row.id, row.name)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </template>
          </u-table>
        </el-tab-pane>
        <el-tab-pane label="已过期" name="fourth">
          <u-table
            :data="list"
            :loading="listLoading"
            :options="listOptions"
            :columns="columns"
            :pagination.sync="listQuery"
            :fetch="hdlList"
            @selection-change="hdlSelectChange"
          >
            <template v-slot:right>
              <el-table-column label="操作" align="center" fixed="right">
                <template slot-scope="{ row }">
                  <el-button type="text" @click="handleEdit(row)">编辑</el-button>
                  <el-dropdown>
                    <el-button type="text">更多</el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="hdlDelete(row.id, row.name)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </template>
          </u-table>
        </el-tab-pane>
      </el-tabs>
    </u-page>

    <u-dialog :title="textMap[dialogStatus]" :show.sync="dialogFormVisible" width="600px" @confirm="dialogStatus==='create'?handleCreate():handleUpdate()">
      <el-form ref="dialogForm" :model="dataForm" :rules="rules" label-width="100px">
        <el-form-item label="优惠券分组" prop="groupId">
          <group v-model="dataForm.groupId" style="width: 100%" active />
        </el-form-item>
        <el-form-item label="模板ID" prop="templateId">
          <el-input v-model="dataForm.templateId" placeholder="优惠券模板ID（注:通联卡劵模板ID）" oninput="value=value.replace(/[^\d]/g,'')" clearable >
            <el-button slot="append" icon="el-icon-search" @click="handleTemplate(dataForm.templateId)" />
          </el-input>
        </el-form-item>
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="dataForm.name" placeholder="请输入优惠券名称" clearable maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="有效期" prop="validityDate">
          <u-date-time-picker v-model="dataForm.validityDate" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="人员权限" prop="roleIds">
          <role v-model="dataForm.roleIds" style="width: 100%" />
        </el-form-item>
        <el-form-item label="发放总量" prop="ifNumLimit">
          <el-radio-group v-model="dataForm.ifNumLimit">
            <el-radio :label="false">不限制</el-radio>
            <el-radio :label="true">限制</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="dataForm.ifNumLimit" label="限制库存" prop="stock">
          <el-input v-model="dataForm.stock" placeholder="请输入库存" style="width: 150px" />
          <span style="margin-left: 10px">张</span>
        </el-form-item>
        <el-form-item label="模板状态" prop="disabled">
          <el-radio-group v-model="dataForm.disabled">
            <el-radio :label="true">正常</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remark" type="textarea" :rows="4" placeholder="请输入优惠券备注" maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>
    </u-dialog>

  </div>
</template>

<script>
import group from '@/components/coupon/group'
import role from '@/components/system/role'
export default {
  components: {
    group,
    role
  },
  data() {
    return {
      api: this.$u.api.MarketCoupon,
      /** 新建优惠券 **/
      dataForm: {
        name: ''
      },
      rules: {
        groupId: [
          { required: true, message: '请选择分组', trigger: 'change' }
        ],
        name: [
          { required: true, message: '优惠券名称必填', trigger: 'blur' }
        ],
        validityDate: [
          { required: true, message: '有效期必填', trigger: 'blur' }
        ],
        templateId: [
          { required: true, message: '模板ID必填', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '限制张数必填', trigger: 'blur' }
        ]
      },
      // 分组列表
      group: [],
      /** 优惠券管理 **/
      listQuery: {
        page: 1,
        pageSize: 10,
        totalCount: 1,
        beginValidityDate: [],
        name: '',
        templateId: '',
        remark: '',
        num: '',
        creatDate: '',
        disabled: '',
        groupId: '',
        beginTime: '',
        endTime: '',
        beginDate1: '',
        beginDate2: '',
        status: ''
      },
      tabActive: 'all',
      creatDate: [],
      disabledList: [
        {
          value: '',
          label: '全部'
        }, {
          value: '1',
          label: '正常'
        }, {
          value: '0',
          label: '禁用'
        }
      ],
      textMap: {
        update: '编辑优惠券',
        create: '新增优惠券'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      // 表格
      columns: [
        {
          prop: 'group',
          label: '分组',
          width: '80',
          formatter: (row, column) => {
            const { group } = row
            if (group) {
              return group.groupName
            }
          }
        },
        {
          prop: 'name',
          label: '名称',
          width: '200'
        },
        {
          prop: 'validityDate',
          label: '有效期日期',
          width: '180',
          render: (h, params) => {
            let { beginDate, endDate } = params.row
            if (!beginDate) {
              beginDate = '不限制'
            }
            if (!endDate) {
              endDate = '不限制'
            }
            return [
              h('el-tag', { props: { effect: 'plain' }}, '起始:' + beginDate),
              h('br'),
              h('el-tag', { props: { effect: 'plain' }}, '终止:' + endDate)
            ]
          }
        },
        {
          prop: 'templateId',
          label: '模板ID',
          width: '80'
        },
        {
          prop: 'stock',
          label: '发放总量',
          width: '100',
          formatter: (row) => {
            if (row.ifNumLimit) {
              return row.stock
            } else {
              return '不限制'
            }
          }
        },
        {
          prop: 'total',
          label: '已领取',
          width: '100'
        },
        {
          prop: 'surplus',
          label: '剩余数量',
          width: '100',
          formatter: (row) => {
            if (row.ifNumLimit) {
              return row.surplus
            } else {
              return '不限制'
            }
          }
        },
        {
          prop: 'createdAt',
          label: '创建时间',
          timestamp: true,
          width: '140'
        },
        {
          prop: 'status',
          label: '状态',
          render: (h, params) => {
            const { status, status_text } = params.row
            let type = 'success'
            switch (status) {
              case 0:
                type = 'warning'
                break
              case 1:
                type = 'success'
                break
              case 2:
                type = 'danger'
                break
              case 3:
                type = 'danger'
                break
            }

            return h('el-tag', { props: { type: type }}, status_text)
          }
        },
        {
          prop: 'remark',
          label: '备注',
          width: '200'
        },
        {
          prop: 'disabled',
          label: '模板状态',
          render: (h, params) => {
            if (params.row.disabled) {
              return h('el-tag', { props: { type: 'success' }}, '正常')
            } else {
              return h('el-tag', { props: { type: 'danger' }}, '禁用')
            }
          }
        }
      ],
      listLoading: false,
      list: [],
      listOptions: {
        stripe: true
      },
      newForm: {
        ifNumLimit: false,
        disabled: true
      }
    }
  },
  created() {
    this.hdlList()
  },
  methods: {
    handleClick(tab) {
      let status = ''
      const { index } = tab
      switch (index) {
        // 全部
        case '0':
          status = ''
          break
        // 发放中
        case '1':
          status = '1'
          break
        // 未发放
        case '2':
          status = '0'
          break
        // 已领完
        case '3':
          status = '3'
          break
        // 已过期
        case '4':
          status = '2'
          break
      }
      this.listQuery.status = status
      this.hdlFilter()
    },
    // 打开新增弹窗
    handleOpen() {
      this.hdlOpen({
        validityDate: [],
        ifNumLimit: false,
        disabled: true
      })
    },
    // 新增事件
    handleCreate() {
      const { validityDate } = this.dataForm
      if (validityDate) {
        this.dataForm.beginDate = validityDate[0]
        this.dataForm.endDate = validityDate[1]
      }
      this.hdlCreate()
    },
    // 打开修改弹窗
    handleEdit(row) {
      const { beginDate, endDate } = row
      row.validityDate = []
      if (beginDate && endDate) {
        row.validityDate = [beginDate, endDate]
      }
      this.hdlEdit(row)
    },
    // 打开修改弹窗
    handleUpdate() {
      const { validityDate } = this.dataForm
      if (validityDate) {
        this.dataForm.beginDate = validityDate[0]
        this.dataForm.endDate = validityDate[1]
      }
      this.hdlUpdate()
    },
    // 创建时间
    changeDate(item) {
      if (item) {
        this.listQuery.beginTime = item[0]
        this.listQuery.endTime = item[1]
      } else {
        this.listQuery.beginTime = ''
        this.listQuery.endTime = ''
      }
    },
    // 有效期起始时间范围
    changeBeginValidityDate(item) {
      if (item) {
        this.listQuery.beginDate1 = item[0]
        this.listQuery.beginDate2 = item[1]
      } else {
        this.listQuery.beginDate1 = ''
        this.listQuery.beginDate2 = ''
      }
    },
    // 模板数据补充
    handleTemplate(templateId) {
      const self = this
      self.api.template({ templateId }).then(res => {
        console.log(res.data)
        const { couponName, validityBeginDate, validityEndDate } = res.data
        const validityArray = [validityBeginDate, validityEndDate]
        self.dataForm.name = couponName
        self.dataForm.beginDate = validityBeginDate
        self.dataForm.endDate = validityEndDate
        self.dataForm.validityDate = validityArray
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  .disabled {
    ::v-deep{
      .el-input{
        width: 140px;
      }
    }
  }
}
/* 表单label 左对齐*/
::v-deep .left-align-show .el-form-item__label::before{
  content: "*";
  color: #ff4949;
  margin-right: 4px;
}
/* 表单label 左对齐*/
::v-deep .left-align-hide .el-form-item__label::before{
  content: "*";
  color: transparent;
  margin-right: 4px;
}
</style>

